﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Samples.ServiceHosting.StorageClient;

using Ciripescu_WebRole.Entities;
using Ciripescu_WebRole.BL;

namespace Ciripescu_WebRole
{
    public partial class join : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //reqUsername.ErrorMessage = Properties.Resources.UsernameRequired;
            if(!IsPostBack)
             divErrors.InnerHtml      = String.Empty;
        }

        protected void btnRegister_Click(object sender, ImageClickEventArgs e)
        {
            UserManager uManag = new UserManager();
            User u = uManag.GetItemByEmail(txtEmail.Text);
            if (u != null)
            {
                divErrors.InnerHtml = Properties.Resources.ErrEmailAddrExists;
                return;
            }
            if (uManag.UserNameExists(txtUsername.Text))
            {
                divErrors.InnerHtml = Properties.Resources.ErrUsernameExists;
                return;
            }
            if (recaptcha.IsValid == false)
            {
                divErrors.InnerHtml = Properties.Resources.ErrBadCaptcha;
                return;
            }

            User usr     = new User(txtUsername.Text.ToLower()); //very important!! Azure tables are case sensitive :|
            usr.FullName = txtFullname.Text;
            usr.Password = Utils.MD5Crypt(txtPassword.Text);
            usr.Email    = txtEmail.Text.ToLower();
            usr.IP       = Request.UserHostAddress;

            usr.PictureUri = (new CBlobStorage()).GetImage(Properties.Settings.Default.DefaultPictureId).Uri.ToString();
            InviteManager im       = new InviteManager();
            uManag.Insert(usr);
            //send welcome message - worker job, enqueue
            MailQueue mq = new MailQueue();
            mq.SendWelcomeMessage(txtEmail.Text,txtFullname.Text);                

            // fiecare user care l-a invitat pe asta trebuie sa-l urmareasca de acuma
            Invite inv = im.GetItem(usr.Email);
            UrmarireManager um = new UrmarireManager();
            if (inv != null)
            {
                if (!string.IsNullOrEmpty(inv.UsersWhoInvitedHim))
                {
                    
                    string[] emailuri = inv.UsersWhoInvitedHim.Split(' ');
                    foreach (string email in emailuri)
                    {
                        User userWhoInvited = uManag.GetItemByEmail(email);
                        if (userWhoInvited != null)                                
                            um.Insert(new Urmarire(userWhoInvited.GetUserName(), usr.GetUserName()));
                    }                        
                }
            }
            if (Request.Cookies["invitationId"] != null)
            {
                string obfs = Request.Cookies["invitationId"].Value;
                string email = Utils.DeObfuscateEmail(obfs);
                if (inv != null) // adaca adresa cu care s-a inregistrat a mai fost vazuta in sistem
                {
                    if (inv.UsersWhoInvitedHim != null)
                        if (!inv.UsersWhoInvitedHim.Contains(email)) // vezi daca cel cu emailul "email" apare ca si cand l-ar fi invitat 
                        {
                            // daca nu apare inseamna ca nu l-a mai invitat mai sus
                            User userWhoInvited = uManag.GetItemByEmail(email);
                            if (userWhoInvited != null)
                                um.Insert(new Urmarire(userWhoInvited.GetUserName(), usr.GetUserName()));
                        }
                }
                else // daca adresa asta e total noua pt sistem sigur nu a mai fost invitat de nimeni
                {
                    User userWhoInvited = uManag.GetItemByEmail(email);
                    if (userWhoInvited != null)
                    {
                        um.Insert(new Urmarire(userWhoInvited.GetUserName(), usr.GetUserName()));
                        // ii trimitem un mail la cel care l-a invitat pe asta sa stie ca
                        //mq.SendNewUrmaritorNotification(userWhoInvited.FullName, userWhoInvited.Email, usr.FullName, usr.Email, userWhoInvited.GetUserName(), usr.GetUserName());
                    }
                }
            }

            Session.Add("UserName", usr.GetUserName()); // login
            //Response.Redirect("~/invita.aspx");
            Response.Redirect("/invita/");
        }       
    }
}
